const iniitalState = {
    //未完成事项数组
    penddingList: [],
    //已完成事项数组
    finishedList: []
}

export function todoReducer(state = iniitalState, action) {
    switch (action.type) {
        //判断为添加代办
        case "addTodo":
            var flag = false;
            //判断是否重复添加待办事项
            state.penddingList.forEach((ele) => {
                if (ele.text === action.text) {
                    window.alert("不可以添加相同的todo")
                    flag = true
                }
            })
            //第一次添加待办事项
            if (!flag) {
                var todo = {
                    text: action.text,
                    status: "PENDDING"
                }
                //追加到代办事项数组
                state.penddingList.push(todo)
            }
            return {
                //同步redux
                penddingList: [...state.penddingList],
                finishedList: state.finishedList
            };
        //判断为已完成
        case "penddingToFinished":
            //将未完成的事项进行删除
            state.penddingList.forEach((ele, index) => {
                if (ele.text === action.todo.text) {
                    state.penddingList.splice(index, 1)
                }
            })
            //改变事项状态
            action.todo.status = "FINSHED"
            //已完成数组添加todo
            state.finishedList.push(action.todo)
            //同步redux
            return {
                penddingList: [...state.penddingList],
                finishedList: [...state.finishedList]
            };
        default:
            return state;
    }
}